package org.com.system.util.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateUtils {

	
	private static SessionFactory sessionFactory=null;
	public static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
	
	public HibernateUtils(SessionFactory sessionFactory){
		HibernateUtils.sessionFactory=sessionFactory;
	}
	
	/**
	 * 得到当前线程的Session
	 * @return Session
	 */
	public Session getSession(){
		Session session=threadLocal.get();
		if(null==session){
			session=sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
	
	/**
	 *关闭当前线程的Session 
	 */
	public void closeSession(){
		Session session=threadLocal.get();
		if(null!=session){
			session.close();
		}
		threadLocal.set(null);
	}
	
	public void closeSessionFactory(){
		if(null!=sessionFactory){
			sessionFactory.close();
		}
	}
}
